package com.flashcash.solu.view.loan;


import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.flashcash.kotlin.utils.FirebaseAnalyticsConstants;
import com.flashcash.kotlin.utils.FirebaseAnalyticsUtils;
import com.flashcash.solu.R;
import com.flashcash.solu.app.base.BaseFragment;
import com.flashcash.solu.bean.HistoryLoanAppInfoBean;
import com.flashcash.solu.common.EventCollection;
import com.flashcash.solu.common.FieldParamsInt;
import com.flashcash.solu.common.TokenManager;
import com.flashcash.solu.view.CustomRecyclerView;
import com.flashcash.solu.view.me.MyLoanActView;
import com.flashcash.solu.view.me.MyLoanAdapter;
import com.flashcash.solu.view.me.presenter.MyLoanActPreImp;
import com.flashcash.solu.view.me.presenter.MyLoanActPresenter;
import com.flashcash.solu.widget.xleotoast.XLeoToast;
import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.x.leo.apphelper.data.cache.CacheDataManage;
import com.x.leo.apphelper.utils.ErrorHandler;
import com.x.leo.refrashviews.OnRefrashAdapter;
import com.x.leo.refrashviews.RefreshLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;

/**
 * Created on 2019-05-12 23:22.
 */
public class MyLoanFragment extends BaseFragment<MyLoanActPresenter> implements MyLoanActView {

    @BindView(R.id.rv_loan)
    CustomRecyclerView mRvLoan;
    @BindView(R.id.rf_myloan)
    RefreshLayout refrashLayout;
    @BindView(R.id.ll_network)
    LinearLayout llNetwork;
    @BindView(R.id.ll_empty)
    LinearLayout llEmpty;

    private MyLoanAdapter adapter;
    private ArrayList<HistoryLoanAppInfoBean> mLoanDatas;
    private boolean firstLoadData = true;

    @Override
    protected MyLoanActPresenter initPresenter() {
        return new MyLoanActPreImp();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_myloan;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {

    }

    @Override
    protected boolean doPreBuildHeader() {
        return true;
    }

    @Override
    protected boolean initHeader(TextView view) {
        view.setText(R.string.textview_my_loan);
        return true;
    }

    @Override
    protected void initData() {
        RxBus.get().register(this);

        mLoanDatas = new ArrayList<>();
//        mIdTextviewTitle.setText(getString(R.string.text_title_myloan));
//        mIdImagebuttonInfoList.setVisibility(View.GONE);
        mRvLoan.setLayoutManager(new LinearLayoutManager(getContext()));
        refrashLayout.setOnRefrashListener(new OnRefrashAdapter() {
            @Override
            public void onTopRefrash() {
                mPresenter.initLoanData();
            }

            @Override
            public void onBottomRefrash() {

            }
        });
        if (TokenManager.getInstance().hasLogin()) {//已登录
            mPresenter.initLoanData();
        } else {
            showEmptyPage();
        }
    }

    /**
     * 刷新数据
     */
    public void requestData() {
        mPresenter.initLoanData();
    }

    @Override
    public void initData(List<HistoryLoanAppInfoBean> historyLoanAppInfoBean) {
        refrashLayout.setVisibility(View.VISIBLE);
        llNetwork.setVisibility(View.GONE);
        llEmpty.setVisibility(View.GONE);
        mLoanDatas.clear();
//        for (HistoryLoanAppInfoBean bean : historyLoanAppInfoBean) {
//            if (!TextUtils.equals(bean.getStatus(), FieldParams.LoanStatus.SUBMITTED)) {
//                mLoanDatas.add(bean);
//            }
//        }
        mLoanDatas.addAll(historyLoanAppInfoBean);
        //XLeoToast.showMessage(mLoanDatas.size() + "");
        if (adapter == null) {
            adapter = new MyLoanAdapter(getContext(), mLoanDatas);
            mRvLoan.setAdapter(adapter);
            adapter.setCallBack(new MyLoanAdapter.CallBack() {
                @Override
                public void onCancelClick(HistoryLoanAppInfoBean historyLoanAppInfoBean) {
                    FirebaseAnalyticsUtils.INSTANCE.logEvent(FirebaseAnalyticsConstants.Event.MYLOAN_CANCEL, null);
                    mPresenter.cancelLoan(historyLoanAppInfoBean.getLoanAppId());
                }

                @Override
                public void onDeleteClick(HistoryLoanAppInfoBean historyLoanAppInfoBean) {

                }
            });
//            mRvLoan.scheduleLayoutAnimation();
        } else {
            adapter.notifyDataSetChanged();
        }
        mRvLoan.scheduleLayoutAnimation();
    }

    @Override
    public void showEmptyPage() {
        refrashLayout.setVisibility(View.GONE);
        llNetwork.setVisibility(View.GONE);
        llEmpty.setVisibility(View.VISIBLE);
    }

    @Override
    public void showNetWorkErrorPage() {
        refrashLayout.setVisibility(View.GONE);
        llNetwork.setVisibility(View.VISIBLE);
        llEmpty.setVisibility(View.GONE);
    }

    /**
     * event posted from: called loginSuccess api successful/failed
     */
    @Subscribe
    public void onLoginSuccess(EventCollection.LoginSuccess event) {
        requestData();
    }

    /**
     * event posted from: called logout api successful/failed
     */
    /*@Subscribe
    public void onLogOut(EventCollection.LogoutEvent event) {
        showEmptyPage();
    }*/
    @Override
    public void onCancelFailed(Throwable e) {
        Objects.requireNonNull(new ErrorHandler.Builder().setContext(Objects.requireNonNull(getContext())).setMessage(TextUtils.isEmpty(e.getMessage()) ? getString(R.string.show_loan_cancel_fail) : e.getMessage())
                .setType(ErrorHandler.HandleType.DIALOG).createHandler()).show();
    }

    @Override
    public void onCancelSuccess() {
        XLeoToast.showMessage(R.string.show_loan_cancel_success);
        CacheDataManage.INSTANCE.addData(FieldParamsInt.LATESTBEAN, null);
        RxBus.get().post(new EventCollection.CancelLoan());
        requestData();
    }

    @Override
    public void onDestroy() {
        RxBus.get().unregister(this);
        super.onDestroy();
    }


    @Override
    public void onResume() {
        super.onResume();
//        mRvLoan.scheduleLayoutAnimation();
//        mRvLoan.smoothScrollToPosition(0);
    }
}
